package com.tianji.promotion.listener;

import com.tianji.common.constants.MqConstants;
import com.tianji.promotion.domain.dto.UserCouponDTO;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.UserCoupon;
import com.tianji.promotion.mapper.CouponMapper;
import com.tianji.promotion.mapper.UserCouponMapper;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Component
public class CouponReceiveListener {

    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private UserCouponMapper userCouponMapper;

    @RabbitListener( bindings = @QueueBinding(
           value=@Queue(name=MqConstants.Queue.COUPON_RECEIVE_QUEUE),
           exchange = @Exchange(name=MqConstants.Exchange.PROMOTION_EXCHANGE, type = ExchangeTypes.DIRECT),
            key = MqConstants.Key.COUPON_RECEIVE
    ))
    @Transactional(rollbackFor = Exception.class)
    public void onCouponReceive(UserCouponDTO msg){
        // 更新优惠券的领用数量
        int result = couponMapper.updateIssueNum(msg.getCouponId());
        // 影响记录的行数，只有>0说明是更新成功了
        if(result > 0){
            // 根据couponId查询数据库
            Coupon coupon = couponMapper.selectById(msg.getCouponId());
            // insert到user_coupon
            UserCoupon uc= new UserCoupon();
            uc.setUserId(msg.getUserId());
            uc.setCouponId(msg.getCouponId());
            if(coupon.getTermDays() != null && coupon.getTermDays() > 0){
                uc.setTermBeginTime(LocalDateTime.now());
                uc.setTermEndTime(LocalDateTime.now().plusDays(coupon.getTermDays()));
            }else{
                uc.setTermBeginTime(coupon.getTermBeginTime());
                uc.setTermEndTime(coupon.getTermEndTime());
            }
            uc.setStatus(1);
            uc.setCreateTime(LocalDateTime.now());
            uc.setUpdateTime(LocalDateTime.now());
            userCouponMapper.insert(uc);
        }
    }
}
